package com.gaofeng.day22.a09ThreadDemo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//public class MyThread extends Thread{
//    static int ticket = 0;
//    // 共享一个锁
//    static Lock lock = new ReentrantLock();
//    @Override
//    public void run() {
//         while (true){
////             synchronized (MyThread.class){
//                 lock.lock();
//                 if (ticket == 100) {
//                     lock.unlock();
//                     break;
//                 } else {
//                     try {
//                         Thread.sleep(100);
//                     } catch (InterruptedException e) {
//                         throw new RuntimeException(e);
//                     }
//                     ticket++;
//                     System.out.println(getName() + "正在卖第 " + ticket + " 张票");
//                 }
//                 lock.unlock();
//             }
////         }
//    }
//}


public class MyThread extends Thread{
    static int ticket = 0;
    // 共享一个锁
    static Lock lock = new ReentrantLock();
    @Override
    public void run() {
        while (true){
            lock.lock();
            try {
                if (ticket == 100) {
                    lock.unlock();
                    break;
                } else {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    ticket++;
                    System.out.println(getName() + "正在卖第 " + ticket + " 张票");
                }
            } catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }

    }
}